<?php

	function MySQL_go($mysql_server,$mysql_user,$mysql_pass) {
		$link = @mysql_connect($mysql_server, $mysql_user, $mysql_pass) or die('Could not connect: ' . mysql_error());
		return $link;
	}
	
	function MySQL_set_db($link,$db) {
		$db_selected = mysql_select_db($db, $link);
		if (!$db_selected) {
			die ('Can\'t use db \''.$db.'\' : ' . mysql_error());
		}
	}
	
	function MySQL_halt($link) {
		mysql_close($link);
	}

	function Page_startup($title,$version) {
		//header("Content-Type: application/xhtml+xml; charset=utf-8");
		echo "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/2002/REC-xhtml1-20020801/DTD/xhtml1-transitional.dtd\">";
		echo "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\">
				<head>
					<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\" />
					<title>".$title." ".$version."</title>
				</head>
				<body>";
	}
	
	function Page_shutdown() {
		echo "</body></html>";
	}
	
	function Page_headbar($user) {
		$timestamp = date("g:i A", time());
		$headbar_r = array (	"0" => $user,
								"1" => "options",
								"2" => "search",
								"3" => "logout",
								"4" => $timestamp);


		$i=0;
		?><table class="head"><tr><td><?php
		while ($i < count($headbar_r)) {
			if ($i > 0 && $i+1<count($headbar_r)) {
				$start="<a href=\"";
				$end=".php\">";
				$a="</a>";
				echo $start.$headbar_r[$i].$end.ucfirst($headbar_r[$i]).$a;
			}
			else { echo ucfirst($headbar_r[$i]); }
			if ($i+1 < count($headbar_r)) { echo " | "; }
			$i++;
		}
		?></td></tr></table><?php
	}
	
	function Home_link () {
		echo "<a href=\"index.php#bot\">Home</a>";
	}

	function Numberify($value) {
		$last = substr($value, -1);
		if ($last > 3) {
			$tail = 'th';
		}
		elseif ($last == '1') {
			$tail = 'st';
		}
		elseif ($last == '2') {
			$tail = 'nd';
		}
		else { $tail = 'rd'; }
		
		return $tail;
	}
	
	function Express_time($olddate) {
		$date = time();
		$diff = $date - $olddate;
		if ($diff == 0) { $diff = 1; } // "0 seconds ago" just sounds weird
		
		if ($diff < 60) {
			$unit = " sec";
			$diff = round($diff);
		}
		elseif (($diff >= 60) && ($diff < 3600)) {
			$unit = " min";
			$diff = round($diff/60);
		}
		elseif (($diff >= 3600) && ($diff < 86400)) {
			$unit = " hr";
			$diff = round($diff/60/60);
		}
		elseif (($diff >= 86400) && ($diff < 604800)) {
			$unit = " day";
			$diff = round($diff/60/60/24);
		}
		elseif (($diff >= 604800) && ($diff < 2592000)) {
			$unit = " week";
			$diff = round($diff/60/60/24/7);
		}
		elseif (($diff >= 2592000) && ($diff < 31536000)) {
			$unit = " month";
			$diff = round($diff/60/60/24/30);
		}
		elseif ($diff >= 31536000) {
			$unit = " year";
			$diff = round($diff/60/60/24/365);
		}
		
		if ($unit != ' min') { $unit .= Singular_plural($diff); }
		$unit = $unit." ";
		return $diff.$unit."ago";
	}
	
	function Singular_plural($val) {
		if ($val!="1") {
			return "s";
		}
	}
	
	function Authenticate() {

		session_name("featherChat-".(dirname($_SERVER[PHP_SELF])));
		session_start();

		require_once 'config.mysql.php';
		
		$link = mysql_connect($mysql_server,$mysql_user,$mysql_pass) or die('Unable to connect to MySQL server: ' . mysql_error());
		mysql_select_db($mysql_db,$link) or die ('Can\'t use db: ' . mysql_error());

		if (isset($_POST[user]) && isset($_POST[pass])) {

			$user = mysql_real_escape_string($_POST[user]);

			$dbusersql = "SELECT `name` FROM `featherchat_users` WHERE `name` = '".$user."'";
			$result = mysql_query($dbusersql);
			$dbuser = @mysql_result($result,0) or die (header("Location: auth.php?url=".$_SERVER[PHP_SELF]."&autherr")); // for punctuation correction; walt vs Walt

			$dbpasssql = "SELECT `pass` FROM `featherchat_users` WHERE `name` = '".$dbuser."'";
			$result = mysql_query($dbpasssql);
			$dbpass = @mysql_result($result,0);

			$pass = mysql_real_escape_string(md5($_POST[pass]));

			if (md5($_POST[pass]) == $dbpass) {
				$_SESSION[featherauth] = '1';
				$_SESSION[user] = $dbuser;

				if ($_POST[remember] == "on") {
					$token = md5(time());
					setcookie("featherCookie-".(dirname($_SERVER[PHP_SELF])),$token, time()+604800); // 7 days
					
					$checkdbsql = "SELECT `user`,`tokenid`,`timestamp` FROM `featherchat_tokens` WHERE `user` = '".$dbuser."'";
					$result = mysql_query($checkdbsql);
					while ($checkdb = @mysql_fetch_assoc($result)) { // remove stale tokens
						if ((time() - $checkdb[timestamp]) > 604800) {
							Drop_token($dbuser,$checkdb[tokenid]);
						}
					}

					$addtokensql = "INSERT INTO `featherchat_tokens` (`user`, `tokenid`,`timestamp`) VALUES ('".$dbuser."', '".$token."', '".time()."')";
					mysql_query($addtokensql) or die ("Unable to add token: ".mysql_error());
				}

				header("Location:".$_GET[url]); //Okay, you may pass...
			}
			else {
				die (header("Location: auth.php?url=".$_SERVER[PHP_SELF]."&autherr"));
			}
		}
		elseif (!empty($_COOKIE["featherCookie-".(dirname($_SERVER[PHP_SELF]))])) {
		
			$token = mysql_real_escape_string($_COOKIE["featherCookie-".(dirname($_SERVER[PHP_SELF]))]);
			$checktokensql = "SELECT `user`,`tokenid` FROM `featherchat_tokens` WHERE `tokenid` = '".$token."'";
			$result = @mysql_query($checktokensql);
			$token_r = mysql_fetch_assoc($result);
			
			if ($_COOKIE["featherCookie-".(dirname($_SERVER[PHP_SELF]))] == $token_r[tokenid]) {
				$_SESSION[featherauth] = '1';
				$_SESSION[user] = $token_r[user];
			}
		}

		mysql_close($link);

		if (!(isset($_SESSION[featherauth]) && $_SESSION[featherauth] == '1')) {
			header("Location: auth.php?url=".$_SERVER[PHP_SELF]);
		}
	}
	
	function Message_print($msg_r,$sessuser,$i,$getcount) {
	
		if ($i%2 == 1) { $bgcolor="#EAF6EA"; } else { $bgcolor="#FFFFFF"; } // To-do: make this configurable

		$message = nl2br(htmlspecialchars(stripslashes($msg_r[message])));
		$user = "<b>".$msg_r['user']."</b>";
		$tdclose = "</td>";
		if ($i==$getcount) {
			$bot=" id=\"bot\"";
		}
		$tdusr = "<td class=\"user\">";
	
		echo "<tr bgcolor=\"".$bgcolor."\"".$bot.">";
		echo $tdusr.$user.": ".$message.$tdclose."<td class=\"time\">".Express_time($msg_r['timestamp']).$tdclose;
			
		echo "\n<td class=\"del\">";
		if ($msg_r[user] == $sessuser) {
			?><a href="delete.php?del=<?php echo $msg_r[msgid]; ?>">del</a><?php
		}
		echo "</td>\n"; ?></tr><?php echo "\n";
	}
	
	function Rand_pass() { // generates a random 8-character string.
		$pass = substr(md5(rand()), 0, 8);
		return $pass;
	}
	
	function Send_email($email_config,$headers,$body) {
	
		require_once 'Mail.php';
		
		$headers[From] = "FeatherChat Notification <".$email_config[email_user].">";

	
		$smtpinfo[host] = $email_config[email_host];
		$smtpinfo[port] = $email_config[email_port];
		$smtpinfo[auth] = true;
		$smtpinfo[username] = $email_config[email_user];
		$smtpinfo[password] = $email_config[email_pass];
		
		$mail_object =& Mail::factory("smtp", $smtpinfo);

		$mail_object->send($headers[To], $headers, $body);

		if (PEAR::isError($mail_object)) {
			echo("<p>" . $mail->getMessage() . "</p>");
		}
		else {
			echo("<p>E-mail successfully sent!</p>");
		}
	}
	
	function Email_notify($email_r,$email_config,$user) {
	
		$headers[To] = $email_r[email];
		$headers[Subject] = "New FeatherChat Message Posted";
		$body = $user." has posted a new item on ".$email_config[featherchataddr]; // Change this to a link later
		
		Send_email($email_config,$headers,$body);	
	}
	
	function Add_user($email_config,$emailaddress,$user,$newuser,$password) {
	
		$newuser = mysql_real_escape_string($newuser);
		$password = mysql_real_escape_string($password);
		$emailaddress = mysql_real_escape_string($emailaddress);
		
		$addusersql = "INSERT INTO `featherchat_users` (`name` , `pass` , `email`) VALUES ('".$newuser."', '".md5($password)."', '".$emailaddress."')";
		mysql_query($addusersql);
		
		if ($email_enable == "1") { // Don't try to send an e-mail if the admin hasn't configured it.
		
			$headers[To] = $emailaddress;
			$headers[Subject] = "FeatherChat User Added";
			$body = $user." has added you as a new user, \"".$newuser."\" on ".$email_config[featherchataddr]."\nYour password is \"".$password."\""; // Change this to a link later
		
			Send_email($email_config,$headers,$body);
		}
		else {
			echo "E-mail notification not configured;<br />Please notify your new user:<br />Username: ".$newuser."<br />Password ".$password;
		}
	}
	
	function Reset_password($email_config,$emailaddress) { // Handles all operations related to resetting a user's password
	
		$newpass = Rand_pass();
		
		$newpass = mysql_real_escape_string($newpass);
		$emailaddress = mysql_real_escape_string($emailaddress);
	
		$headers[From] = "FeatherChat Notification <".$email_config[email_user].">";
		$headers[To] = $emailaddress;
		$headers[Subject] = "FeatherChat Password Reset";
		$body = "Your new FeatherChat password is \"".$newpass."\" for ".$email_config[featherchataddr];
		
		$sendstring = "UPDATE `featherchat_users` SET `pass` = '".md5($newpass)."' WHERE `email` = '".$emailaddress."'";
		mysql_query($sendstring) or die ("Unable to update password");
		
		Send_email($email_config,$headers,$body);
	}
	
	function Get_userlevel($user) {
	
		$user = mysql_real_escape_string($user);
		
		$userlevelsql = "SELECT `level` FROM `featherchat_users` WHERE `name` = '".$user."'";
		$result = mysql_query($userlevelsql);
		$userlevel = mysql_result($result,0);
		return $userlevel;
	}
	
	function Check_for_PEAR_Mail() {

		$paths = explode(PATH_SEPARATOR, get_include_path());

		$mailpath = 0;
		foreach($paths as $path) {
			if (file_exists($path."/Mail.php")) {
				$mailpath = "1";
			}
		}
		return $mailpath;
	}
	
	function Email_config_form($target) {
	
		require 'config.mail.php';
		?><script type="text/javascript">
			function checkifunchecked(){
				if (document.mail.enable.checked==false) {
					document.mail.emailhost.disabled=true;
					document.mail.emailuser.disabled=true;
					document.mail.emailpass.disabled=true;
					document.mail.emailport.disabled=true;
					document.mail.featherchataddr.disabled=true;
				}
				else {
					document.mail.emailhost.disabled=false;
					document.mail.emailuser.disabled=false;
					document.mail.emailpass.disabled=false;
					document.mail.emailport.disabled=false;
					document.mail.featherchataddr.disabled=false;
				}
			}
			if (document.all || document.getElementById)
				setInterval("checkifunchecked()",100)
		</script>

		<p>Configure your server's e-mail function:
			<form method="post" action="<?php echo $target; ?>" name="mail">
				Enable e-mail notification? <input type="checkbox" name="enable" <?php if ($email_enable == "1") { echo "checked "; } ?>/><br />
				Host: <input type="text" name="emailhost" <?php if (!empty($email_config[email_host])) { echo "value=\"".$email_config[email_host]."\" "; } ?> /> (Make sure to include ssl:// if you are using SSL)<br />
				User: <input type="text" name="emailuser" <?php if (!empty($email_config[email_user])) { echo "value=\"".$email_config[email_user]."\" "; } ?>/><br />
				Password: <input type="password" name="emailpass" /><br />
				Port: <input type="text" name="emailport"  <?php if (!empty($email_config[email_port])) { echo "value=\"".$email_config[email_port]."\" "; } ?>/> (25 for standard SMTP, 465 for SSL)<br />
				FeatherChat installation address: <input type="text" size="40" name="featherchataddr" <?php if (!empty($email_config[featherchataddr])) { echo "value=\"".$email_config[featherchataddr]."\" "; } else { echo "value=\"http://\" "; } ?>/> (For inclusion in e-mails) <br />
				<input type="submit" value="Go"/>
			</form>
		</p><?php
	}
	
	function Drop_token($user,$token) {
		$droptokensql = "DELETE FROM `featherchat_tokens` WHERE `user` = '".$user."' AND `tokenid` = '".$token."'";
		@mysql_query($droptokensql);
	}
	
?>
